package com.ericsson.enap.modules.kpi.service.impl;

import com.ericsson.common.util.DateUtils;
import com.ericsson.enap.modules.kpi.entity.EnipMeasInfo;
import com.ericsson.enap.modules.kpi.entity.EnipMeasValue;
import com.ericsson.enap.modules.kpi.entity.ImsFiveKpi;
import com.ericsson.enap.modules.kpi.service.EnipKpiFileProcess;
import com.jcraft.enipjsch.ChannelExec;
import com.jcraft.enipjsch.JSch;
import com.jcraft.enipjsch.Session;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.*;

/**
 * UDM类型网元五分钟指标处理
 */
@Component
public class KpiFileProcessUDMFIVEImpl implements EnipKpiFileProcess {

    public List<File> download(ImsFiveKpi imsFiveKpi, String localDir, Logger log,Date date, int delay) {
        return null;
    }

    @Override
    public Map<String, List<File>> download(ImsFiveKpi imsFiveKpi, String localDir, Logger log, Date date) {
        log.info("===================================================  start KpiFileProcessUDMUDRFIVEImpl Files");
        String beginTime = DateUtils.getStatisTime(0, date, "yyyyMMdd_HHmm");
        TreeMap<String, List<File>> fileMap = new TreeMap<>();
        List<File> fileList;
        Session session = null;
        ChannelExec channelExec = null;
        ChannelExec channelExecErrorLog = null;
        BufferedReader input = null;
        BufferedReader inputErrorLog = null;
        try {
            JSch jsch = new JSch();
            session = jsch.getSession(imsFiveKpi.getUsername(), imsFiveKpi.getIp4(), 22);
            session.setConfig("kex", "diffie-hellman-group1-sha1,diffie-hellman-group14-sha1,diffie-hellman-group-exchange-sha1,diffie-hellman-group-exchange-sha256");
            session.setConfig("StrictHostKeyChecking", "no");
            session.setPassword(imsFiveKpi.getPassword());
            session.connect();

            //--getKpi----
            channelExec = (ChannelExec) session.openChannel("exec");
            channelExec.setCommand("bash /home/er_wutao/5gcsts.sh --kpi -p 10 -i 5 ");
            //channelExec.setCommand("cat /opt/yanghai/udm/udm01.txt ");
            channelExec.setInputStream(null);
            input = new BufferedReader(new InputStreamReader(channelExec.getInputStream()));
            channelExec.connect();
            StringBuilder sb = new StringBuilder();
            String line;
            String last = "1";
            int spaceCount = 0;
            while ((line = input.readLine()) != null) {
                if (spaceCount != 0) {
                    if (!last.equals("") || !line.equals("")) {
                        sb.append(line).append("\n");
                    }
                    last = line;
                }
                if (line.contains("get KPI:")) {
                    spaceCount = spaceCount + 1;
                }
            }
            fileList = new ArrayList<>();
            File udmUdrFile = new File(localDir + File.separator + beginTime + ".log");
            FileUtils.write(udmUdrFile, sb.toString(), "utf-8", false);
            fileList.add(udmUdrFile);

            //--getError----
            channelExecErrorLog = (ChannelExec) session.openChannel("exec");
            channelExecErrorLog.setCommand("bash /home/er_wutao/5gcsts.sh --error -p 10 -i 5 ");
            //channelExecErrorLog.setCommand("cat /opt/yanghai/udm/udm01_error.txt ");
            inputErrorLog = new BufferedReader(new InputStreamReader(channelExecErrorLog.getInputStream()));
            channelExecErrorLog.setInputStream(null);
            StringBuilder sbErrorLog = new StringBuilder();
            channelExecErrorLog.connect();
            String lineErrorLog;
            String lastErrorLog = "1";
            int spaceCountErrorlog = 0;
            while ((lineErrorLog = inputErrorLog.readLine()) != null) {
                if (spaceCountErrorlog != 0) {
                    if (!lastErrorLog.equals("") || !lineErrorLog.equals("")) {
                        sbErrorLog.append(lineErrorLog).append("\n");
                    }
                    lastErrorLog = lineErrorLog;
                }
                if (lineErrorLog.contains("get Error:")) {
                    spaceCountErrorlog = spaceCountErrorlog + 1;
                }
            }
            File udmUdrErrorFile = new File(localDir + File.separator + beginTime + "_error.log");
            FileUtils.write(udmUdrErrorFile, sbErrorLog.toString(), "utf-8", false);
            fileList.add(udmUdrErrorFile);

            fileMap.put(beginTime, fileList);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("UDMUDR:" + e.getMessage(), e);
        } finally {
            try {
                input.close();
            } catch (IOException e) {
                log.error("input:" + e.getMessage(), e);
                e.printStackTrace();
            }

            try {
                inputErrorLog.close();
            } catch (IOException e) {
                log.error("input:" + e.getMessage(), e);
                e.printStackTrace();
            }

            if (channelExec != null && !channelExec.isClosed()) {
                channelExec.disconnect();
            }
            if (channelExecErrorLog != null && !channelExecErrorLog.isClosed()) {
                channelExecErrorLog.disconnect();
            }
            if (session != null && session.isConnected()) {
                session.disconnect();
            }
        }
        return fileMap;
    }
//    public Map<String, List<File>> download(ImsFiveKpi imsFiveKpi, String localDir, Logger log, Date date) {
//        log.info("===================================================  start download Files");
//        String lastDownTime = ((VgcFifKpi)imsFiveKpi).getLastDownTime();
//        FTPInfoVO ftpInfo = new FTPInfoVO();
//        ftpInfo.setHost(imsFiveKpi.getIp4());
//        ftpInfo.setUserName(imsFiveKpi.getUsername());
//        ftpInfo.setPassword(imsFiveKpi.getPassword());
//        ftpInfo.setPath(imsFiveKpi.getDownloadPath());
//        ftpInfo.setPort(9022);
//        TreeMap<String,List<File>> fileMap = new TreeMap<>();
//        List<File> fileList;
//        SFtpCarrierUtil sftpCarrier = new SFtpCarrierUtil(ftpInfo, log);
//        try {
//            sftpCarrier.connect();
//            Vector v = sftpCarrier.listFiles(ftpInfo.getPath());
//            Collections.sort(v);
//            if (v.size() > 0) {
//                if(null!=lastDownTime&&!"".equals(lastDownTime)) {
//                    Iterator it = v.iterator();
//                    while (it.hasNext()) {
//                        ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) it.next();
//                        String filename = entry.getFilename();
//                        SftpATTRS attrs = entry.getAttrs();
//                        if (!attrs.isDir()) {
//                            if (filename.length() > 33 && filename.contains("gz")
//                                    && (filename.substring(0,14).compareTo(lastDownTime))>0) {
//                                int startTime=Integer.parseInt(filename.substring(12,14));
//                                int endTime=Integer.parseInt(filename.substring(22,24));
//                                if((endTime-startTime)==5||(endTime-startTime)==-55) {
//                                    File tempFile = sftpCarrier.downloadFileKpi(ftpInfo.getPath(), filename, localDir, filename);
//                                    if (null != tempFile) {
//                                        String timeKey = filename.substring(0, 14);
//                                        if (fileMap.containsKey(timeKey)) {
//                                            fileMap.get(timeKey).add(tempFile);
//                                        } else {
//                                            fileList = new ArrayList<>();
//                                            fileList.add(tempFile);
//                                            fileMap.put(timeKey, fileList);
//                                        }
//                                    }
//                                }
//                            }
//                        }
//                    }
//                }else{
//                    Collections.sort(v,Collections.reverseOrder());
//                    Iterator it = v.iterator();
//                    while (it.hasNext()) {
//                        ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) it.next();
//                        String filename = entry.getFilename();
//                        SftpATTRS attrs = entry.getAttrs();
//                        if (!attrs.isDir()) {
//                            if (filename.length() > 33 && filename.contains("gz")) {
//                                int startTime=Integer.parseInt(filename.substring(12,14));
//                                int endTime=Integer.parseInt(filename.substring(22,24));
//                                if((endTime-startTime)==5||(endTime-startTime)==-55) {
//                                    File tempFile = sftpCarrier.downloadFileKpi(ftpInfo.getPath(), filename, localDir, filename);
//                                    if (null != tempFile) {
//                                        String timeKey = filename.substring(0, 14);
//                                        fileList = new ArrayList<>();
//                                        fileList.add(tempFile);
//                                        fileMap.put(timeKey, fileList);
//                                        break;
//                                    }
//                                }
//                            }
//                        }
//                    }
//                }
//            }
//        } catch (SftpException e) {
//            e.printStackTrace();
//        } finally {
//            sftpCarrier.disconnect();
//        }
//        return fileMap;
//    }

    /**
     * 解析文件
     * @param files
     * @param log
     * @return
     */
    public List<EnipMeasInfo> analysis(List<File> files, Logger log) {
        List<EnipMeasInfo> meansInfoList = new ArrayList<>();
        for (File file : files) {
            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new FileReader(file));
                String tempStr;
                int spaceCount = 0;
                EnipMeasInfo mi = new EnipMeasInfo();
                Map<String, String> mtMap = new HashMap<>();
                Map<String, String> tmpMtMap = new HashMap<>();
                String beginTime = "";
                String lastStr = "";
                if (!file.getName().contains("error")) {//读取普通格式kpi文件
                    EnipMeasValue measValue = new EnipMeasValue();
                    Map<String, String> rMap = new HashMap<>();
                    while ((tempStr = reader.readLine()) != null) {
                        if (tempStr.contains(":~>")) {
                            break;
                        }
                        if (spaceCount % 2 == 1 && !tempStr.equals("")) {//key
                            mtMap.put(tempStr.split(" ")[1], String.valueOf(mtMap.size() + 1));
                        }
                        if (spaceCount != 0 && spaceCount % 2 == 0 && !lastStr.equals("") && tempStr.equals("")) {
                            String[] valueStr = lastStr.replaceAll(" +", " ").split(" ");
                            beginTime = valueStr[0].replace("_", " ").substring(0, 19);
                            for (String v : valueStr) {
                                if (!v.contains("-") && !v.contains("%"))
                                    rMap.put(String.valueOf(rMap.size() + 1), v);
                            }
                        }
                        if (tempStr.trim().equals("")) {
                            spaceCount = spaceCount + 1;
                        }
                        lastStr = tempStr;
                    }
                    measValue.setMeasObjLdn("measObjLdn");
                    measValue.setRMap(rMap);
                    Map<String, EnipMeasValue> mvMap = mi.getMeasValueMap();
                    mvMap.put("measObjLdn", measValue);
                } else {//读取error格式文件
                    String job="";
                    while ((tempStr = reader.readLine()) != null) {
                        if (tempStr.contains(":~>")) {
                            break;
                        }
                        if (spaceCount % 2 == 1 && !tempStr.equals("")) {//key
                            if(tempStr.startsWith("job=\"eric")){
                                job=tempStr;
                            }else {
                                String key = job + tempStr.substring(tempStr.indexOf(" ")).trim();
                                mtMap.put(key, String.valueOf(mtMap.size() + 1));
                                tmpMtMap.put(String.valueOf(tmpMtMap.size() + 1), key);
                            }
                        }
                        if (spaceCount != 0 && spaceCount % 2 == 0 && !lastStr.equals("") && tempStr.equals("")) {
                            String[] valueStr = lastStr.replaceAll(" +", " ").split(" ");
                            beginTime = valueStr[0].replace("_", " ").substring(0, 19);
                            for (String v : valueStr) {
                                if (!v.contains("-") && !v.contains("%")) {
                                    EnipMeasValue measValue = new EnipMeasValue();
                                    Map<String, String> rMap = new HashMap<>();
                                    rMap.put(String.valueOf(1), v);
                                    measValue.setMeasObjLdn(tmpMtMap.get(String.valueOf(mi.getMeasValueMap().size() + 1)));
                                    measValue.setRMap(rMap);
                                    Map<String, EnipMeasValue> mvMap = mi.getMeasValueMap();
                                    mvMap.put(measValue.getMeasObjLdn(), measValue);
                                }
                            }
                        }
                        if (tempStr.trim().equals("")) {
                            spaceCount = spaceCount + 1;
                        }
                        lastStr = tempStr;
                    }
                }

                mi.setMeasTypeMap(mtMap);
                //mi.setBeginTime(beginTime);
                mi.setBeginTime("");//采用程序运行时间作为指标时间
                meansInfoList.add(mi);
            } catch (IOException e) {
                log.error("KpiFileProcessUDMUDRFIVEImpl" + e.getMessage());
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e1) {
                        log.error("KpiFileProcessUDMUDRFIVEImpl" + e1.getMessage());
                    }
                }
            }
        }
        return meansInfoList;
    }
//    public List<EnipMeasInfo> analysis(List<File> files, Logger log){
//        List<EnipMeasInfo> meansInfoList = new ArrayList<>();
//        for(File file:files) {
//            SAXReader reader = new SAXReader();
//            Document doc = null;
//            try {
//                doc = reader.read(file);
//            } catch (DocumentException e) {
//                e.printStackTrace();
//            }
//            Element measData = doc.getRootElement().element("measData");
//            String beginTime = doc.getRootElement().element("fileHeader").element("measCollec").attributeValue("beginTime");
//            beginTime = beginTime.substring(0, beginTime.indexOf("+")).replace("T", " ");
//            List<?> measInfoList = measData.elements("measInfo");
//            for (Iterator<?> it = measInfoList.iterator(); it.hasNext(); ) {
//                EnipMeasInfo mi = new EnipMeasInfo();
//                Element measInfo = (Element) it.next();
//                String measInfoId = measInfo.attributeValue("measInfoId");
//
//                Element jobNode = measInfo.element("job");
//                String jobId = jobNode.attributeValue("jobId");
//
//                List<?> measTypeList = measInfo.elements("measType");
//                Map<String, String> mtMap = new HashMap<>();
//                for (Iterator<?> mt = measTypeList.iterator(); mt.hasNext(); ) {
//                    Element measTypeNode = (Element) mt.next();
//                    String p = measTypeNode.attributeValue("p");
//                    String text = measTypeNode.getText();
//                    mtMap.put(text, p);
//                }
//
//                List<?> measValueList = measInfo.elements("measValue");
//                for (Iterator<?> mv = measValueList.iterator(); mv.hasNext(); ) {
//                    EnipMeasValue measValue = new EnipMeasValue();
//                    Element measValueNode = (Element) mv.next();
//                    String measObjLdn = measValueNode.attributeValue("measObjLdn");
//                    List<?> rList = measValueNode.elements("r");
//                    Map<String, String> rMap = new HashMap<>();
//                    for (Iterator<?> r = rList.iterator(); r.hasNext(); ) {
//                        Element rNode = (Element) r.next();
//                        if("".equals(rNode.getText())){
//                            rMap.put(rNode.attributeValue("p"), "0");
//                        }else {
//                            rMap.put(rNode.attributeValue("p"), rNode.getText());
//                        }
//                    }
//                    measValue.setMeasObjLdn(measObjLdn);
//                    measValue.setRMap(rMap);
//                    Map<String, EnipMeasValue> mvMap = mi.getMeasValueMap();
//                    mvMap.put(measObjLdn, measValue);
//                }
//
//                mi.setMeasInfoId(measInfoId);
//                mi.setJobId(jobId);
//                mi.setMeasTypeMap(mtMap);
//                mi.setBeginTime(beginTime);
//                meansInfoList.add(mi);
//            }
//        }
//        return meansInfoList;
//    }

    @Override
    public File download(ImsFiveKpi imsFiveKpi, String localDir, Logger log) {
        return null;
    }

    @Override
    public boolean needUncompress() {
        return true;
    }

    @Override
    public NetType getNetType() {
        return NetType.udm;
    }
}
